package org.example.executor.statement;

import lombok.extern.slf4j.Slf4j;
import org.example.executor.Executor;
import org.example.mapping.BoundSql;
import org.example.mapping.MappedStatement;
import org.example.session.ResultHandler;
import org.example.session.RowBounds;

import java.sql.*;
import java.util.List;

public class PreparedStatementHandler extends BaseStatementHandler {

    public PreparedStatementHandler(Executor wrapper, MappedStatement ms, Object parameter,RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        super(wrapper, ms, parameter,rowBounds, resultHandler, boundSql);
    }

    @Override
    public PreparedStatement prepare(Connection connection) throws SQLException {
        PreparedStatement statement = null;
        try {
            statement = instantiateStatement(connection);
            return statement;
        } catch (SQLException e) {
            closeStatement(statement);
            throw e;
        } catch (Exception e) {
            closeStatement(statement);
            throw new RuntimeException("Error preparing statement.  Cause: " + e);
        }
    }

    @Override
    public void parameterize(Statement statement) {
        try {
            parameterHandler.setParameters((PreparedStatement) statement);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    protected PreparedStatement instantiateStatement(Connection connection) throws SQLException {
        String sql = boundSql.getSql();
        return connection.prepareStatement(sql);
    }
    private void closeStatement(Statement statement) {
        try {
            statement.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
        PreparedStatement ps = (PreparedStatement) statement;
        boolean execute = ps.execute();
        return resultSetHandler.handleResultSets(ps);
    }
}